package thread2;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-08-19
 * Time: 21:47
 */
public class ThreadDemo7 {
    /*
    volatile 和 synchronized 有着本质的区别。 synchronized 能够保证原子性,
    volatile 保证的是内存可见性，不能保证原子性，也就不能保证线程安全。
     */
    private volatile static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        //创建两个对象
        Object locker1 = new Object();
        Object locker2 = new Object();


        //创建两个线程，每个线程对count加5W次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        //创建了两个对象，结果还是错误的，存在线程安全问题
        System.out.println("count = " + count);
    }
}
